//
//  Copyright © 2016年 yxiang. All rights reserved.
//


#import "YXInfiniteScrollView.h"

@interface YXInfiniteScrollView () <UICollectionViewDataSource,UICollectionViewDelegate> {
    NSInteger _itemCount;
    NSTimeInterval _timeInterval;
    NSInteger _currentPageNumber;
    BOOL _scrollToBack;
}

@property (nonatomic, assign) id <YXInfiniteScrollViewDelegate> delegate;
@property (nonnull ,nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewLayout *layout;
@property (nonatomic, strong) NSTimer *timer;
/// 是否需要循环显示，如果当前有且仅有一张，无论设置为YES还是NO都不会循环。默认为NO，不循环显示。
@property (nonatomic, assign) BOOL needLoop;

@end

@implementation YXInfiniteScrollView

@synthesize timeInterval = _timeInterval;

#pragma mark - 初始化方法
+ (instancetype)infiScrViewWithFrame:(CGRect)frame delegate:(id<YXInfiniteScrollViewDelegate>)delegate collectionViewLayout:(UICollectionViewLayout *)layout scrollType:(InfiScrollType)type {
    YXInfiniteScrollView *view = [[self alloc] initWithFrame:frame WithFlowLayout:layout];
    view.delegate = delegate;
    if (type == InfiScrollType_Ressort) {
        view.needLoop = NO;
    }else {
        view.needLoop = YES;
    }
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame WithFlowLayout:(UICollectionViewLayout *)layout {
    if ([super initWithFrame:frame]) {
        _currentPageNumber = 0;
        _timeInterval = 0;
        _itemCount = 0;
        self.layout = layout;
        [self initUI];
    }
    return self;
}

#pragma mark - 界面方法
- (void)initUI {
    [self addSubview:self.collectionView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
}

#pragma mark - timer方法
- (void)runTimer:(NSTimer *)sender {
    if (!_needLoop) {
        [_collectionView setContentOffset:[self contentOffsetWithCurrentPage]
                                 animated:YES];
    }else {
        [_collectionView setContentOffset:CGPointMake(++ _currentPageNumber * CGRectGetWidth(self.frame), 0)
                                 animated:YES];
    }
}

- (CGPoint)contentOffsetWithCurrentPage {
    
    if (_scrollToBack) {
        -- _currentPageNumber;
    }else {
        ++ _currentPageNumber;
    }
    
    if (_currentPageNumber == _itemCount-1) {
        _scrollToBack = YES;
    }else if (_currentPageNumber == 0) {
        _scrollToBack = NO;
    }
    
    return CGPointMake(_currentPageNumber * CGRectGetWidth(self.frame), 0);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_delegate && [_delegate respondsToSelector:@selector(itemNumberInInfi:)]) {
        _itemCount = [_delegate itemNumberInInfi:self];
        if (_itemCount <= 1) {
            [_timer invalidate];
            _timer = nil;
            _needLoop = NO;
        }
        if (_needLoop) {
            _currentPageNumber = 1;
            [collectionView setContentOffset:CGPointMake(CGRectGetWidth(self.frame)*_currentPageNumber, 0)];
            _itemCount += 2;
        }
        return _itemCount;
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_delegate && [_delegate respondsToSelector:@selector(itemForInfi:index:)]) {
        if (_needLoop) {
            if (indexPath.row == _itemCount-1 || indexPath.row == 1) {
                return [_delegate itemForInfi:self index:0];
            }else if (indexPath.row == _itemCount-2 || indexPath.row == 0) {
                return [_delegate itemForInfi:self index:_itemCount-3];
            }
            return [_delegate itemForInfi:self index:indexPath.row-1];
        }else {
            return [_delegate itemForInfi:self index:indexPath.row];
        }
    }
    return nil;
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_delegate && [_delegate respondsToSelector:@selector(itemDidSelectedWithInfi:forIndex:)]) {
        if (_needLoop) {
            if (indexPath.row == _itemCount-1 || indexPath.row == 1) {
                [_delegate itemDidSelectedWithInfi:self forIndex:0];
            }else if (indexPath.row == _itemCount-2 || indexPath.row == 0) {
                [_delegate itemDidSelectedWithInfi:self forIndex:_itemCount-3];
            }else
                [_delegate itemDidSelectedWithInfi:self forIndex:indexPath.row-1];
        }else {
            [_delegate itemDidSelectedWithInfi:self forIndex:indexPath.row];
        }
    }
    return YES;
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_timer invalidate];
    _timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.timer fireDate];
}

/// 动画结束时调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self refreshLimitScrollWithScrollView:scrollView];
}

/// 手动拖拽结束后，减速完成后调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self refreshLimitScrollWithScrollView:scrollView];
}

- (void)refreshLimitScrollWithScrollView:(UIScrollView *)scrollView {
    if (_itemCount <=1) return;
    _currentPageNumber = scrollView.contentOffset.x/CGRectGetWidth(self.frame);
    if (_needLoop) {
        if (_currentPageNumber == _itemCount-1) {
            _currentPageNumber = 1;
        }else if (_currentPageNumber == 0) {
            _currentPageNumber = _itemCount-2;
        }
        [scrollView setContentOffset:CGPointMake(_currentPageNumber*CGRectGetWidth(self.frame), 0)];
    }else {
        if (_currentPageNumber == _itemCount-1) {
            _scrollToBack = YES;
        }else if (_currentPageNumber == 0) {
            _scrollToBack = NO;
        }
    }
}

- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - Setter&Getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
        _collectionView.pagingEnabled = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}
- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(runTimer:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}
- (NSTimeInterval)timeInterval {
    if (!_timeInterval) _timeInterval = 0;
    return _timeInterval;
}
- (void)setTimeInterval:(NSTimeInterval)timeInterval {
    _timeInterval = timeInterval;
    if (_timeInterval != 0) {
        [self.timer fireDate];
    }
}

@end
